package com.artibata.eagent.ui.springmvc.controller;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.artibata.eagent.domain.Flight;
import com.artibata.eagent.service.AirlineService;

@Controller
public class SearchController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource(name = "airlineServices")
    private Map<String, String> airlineServices;
	
	@ModelAttribute("airlines")
	public Collection<String> availableAirlines(){
		logger.debug("Available airlines : {}", airlineServices.size());
		return airlineServices.values();
	}
	
	@RequestMapping(value="/search/flight", method=RequestMethod.POST)
	public ModelMap search(
			HttpServletRequest request,
			@RequestParam String airline, 
			@RequestParam @DateTimeFormat(iso=ISO.DATE) Date departure, 
			@RequestParam String origin, 
			@RequestParam String destination, 
			@RequestParam Integer adult, 
			@RequestParam Integer child, 
			@RequestParam Integer infant){
		
		AirlineService service = (AirlineService) WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(airline);
		if(service == null) {
			throw new IllegalArgumentException("Airline "+airline+" not supported");
		}
		List<Flight> flights = service.search(departure, origin, destination, adult, child, infant);
		return new ModelMap(flights);
	}
}
